package top.abrsm.util;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import top.abrsm.entity.bo.PushBuyMessageBo;

import java.util.Arrays;
import java.util.List;

/**
 * 推送微信消息工具类
 */
@Slf4j
public class PushMessageUtil {


    /**
     * 小程序采购消息通知
     * @param openId
     * @param templateId
     * @param pushBuyMessageBo
     * @return
     */
    public static String pushBuyMessage ( String openId, String templateId, PushBuyMessageBo pushBuyMessageBo ) {
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl ();
        // 公众号appId
        configStorage.setAppId ( ConstUtil.PUBLIC_AppID );
        // 公众号appSecret
        configStorage.setSecret ( ConstUtil.PUBLIC_AppSecret );

        WxMpService wxMpService = new WxMpServiceImpl ();
        wxMpService.setWxMpConfigStorage ( configStorage );

        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage ();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId ( templateId );
        //设置发送给哪个用户xxxxxxxxxxx");
        wxMpTemplateMessage.setToUser ( openId );
        wxMpTemplateMessage.setUrl ( null );
        //构建消息格式
        List<WxMpTemplateData> list = Arrays.asList (
                new WxMpTemplateData ( "first", pushBuyMessageBo.getTitle () ),
                new WxMpTemplateData ( "keyword1", pushBuyMessageBo.getBuyTitle () ),
                new WxMpTemplateData ( "keyword2", pushBuyMessageBo.getStartTime () ),
                new WxMpTemplateData ( "keyword3", pushBuyMessageBo.getEndTime () ),
                new WxMpTemplateData ( "keyword4", pushBuyMessageBo.getResult () ),
                new WxMpTemplateData ( "remark", pushBuyMessageBo.getRemark () )
        );
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData ( list );
        try {
            //发送模板
            wxMpService.getTemplateMsgService ().sendTemplateMsg ( wxMpTemplateMessage );
        } catch ( WxErrorException e ) {
            e.printStackTrace ();
            log.error ( "推送失败 -> [{}]", e );
        }
        System.out.println ( "消息推送成功" );
        return "success";
    }


}
